"""
简单直观地解释 char_index[char] = right 的作用
"""


def explain():
    s = "abca"
    print("\n" + "=" * 80)
    print(f"示例：字符串 '{s}'")
    print("=" * 80)

    char_index = {}
    left = 0

    print("\n问题：当我们遇到重复字符时，如何知道它上次出现在哪里？")
    print("答案：用字典 char_index 记录每个字符最后出现的索引！\n")

    for right, char in enumerate(s):
        print(f"\n步骤 {right + 1}: 当前字符 '{char}' (索引 {right})")
        print("-" * 60)

        # 检查是否重复
        if char in char_index and char_index[char] >= left:
            old_pos = char_index[char]
            print(f"⚠️  '{char}' 重复了！上次出现在索引 {old_pos}")
            print(f"   窗口左边界移动: {left} → {old_pos + 1}")
            left = old_pos + 1
        else:
            if char in char_index:
                print(f"✓ '{char}' 虽然出现过(索引{char_index[char]})，但不在窗口内")
            else:
                print(f"✓ '{char}' 第一次出现")

        # 关键：更新字符位置
        print(f"\n💡 执行: char_index['{char}'] = {right}")
        print(f"   意思：记录字符 '{char}' 最后出现在索引 {right}")
        char_index[char] = right

        print(f"\n   字典现在是: {char_index}")
        print(f"   当前窗口: '{s[left:right+1]}' (范围 [{left}, {right}])")


def why_update_every_time():
    print("\n\n" + "=" * 80)
    print("为什么即使字符重复了，也要更新 char_index？")
    print("=" * 80)

    s = "abba"
    print(f"\n示例：'{s}'")
    print("\n如果不更新会怎样？")

    char_index = {}
    left = 0

    for right, char in enumerate(s):
        print(f"\n步骤 {right}: 字符 '{char}'")

        if char in char_index and char_index[char] >= left:
            print(f"  重复！char_index['{char}'] = {char_index[char]}")
            left = char_index[char] + 1

        # 假设我们"忘记"更新第3步的 'b'
        if right == 2:  # 索引2是第二个'b'
            print(f"  ❌ 假设我们忘记更新 char_index['b']")
            print(f"     char_index 仍然是: {char_index}")
        else:
            char_index[char] = right
            print(f"  ✓ 更新 char_index['{char}'] = {right}")
            print(f"     char_index 现在是: {char_index}")

        print(f"     窗口: '{s[left:right+1]}'")

    print("\n结论：必须【每次都更新】，否则记录的位置是过时的！")


def visual_example():
    print("\n\n" + "=" * 80)
    print("可视化示例：'abcabc'")
    print("=" * 80)

    s = "abcabc"
    char_index = {}
    left = 0
    max_len = 0

    for right, char in enumerate(s):
        # 显示字符串
        print(f"\n步骤 {right}:")
        display = ""
        for i, c in enumerate(s):
            if i == right:
                display += f"[{c}]"
            else:
                display += f" {c} "
        print(f"  字符串: {display}")
        print(f"  索引:    0  1  2  3  4  5")

        # 显示窗口
        window_display = "  窗口:   "
        for i in range(len(s)):
            if i == left and i == right:
                window_display += " ⇅ "
            elif i == left:
                window_display += " ⇑ "
            elif i == right:
                window_display += " ⇓ "
            elif left < i < right:
                window_display += " │ "
            else:
                window_display += "   "
        print(window_display)

        # 处理逻辑
        if char in char_index and char_index[char] >= left:
            old_left = left
            left = char_index[char] + 1
            print(f"  ⚠️  '{char}' 重复，left: {old_left} → {left}")

        char_index[char] = right  # 关键：更新位置
        current_len = right - left + 1
        max_len = max(max_len, current_len)

        print(f"  char_index['{char}'] = {right}  (记录位置)")
        print(f"  字典: {char_index}")
        print(f"  当前窗口: '{s[left:right+1]}' (长度 {current_len})")
        print(f"  最大长度: {max_len}")


if __name__ == "__main__":
    explain()
    why_update_every_time()
    visual_example()

    print("\n\n" + "=" * 80)
    print("核心要点")
    print("=" * 80)
    print("1️⃣  char_index[char] = right  的作用：")
    print("    记录字符 char 最后一次出现的位置是 right")
    print()
    print("2️⃣  为什么需要这个字典？")
    print("    当遇到重复字符时，需要知道它上次出现在哪里")
    print("    这样才能知道左边界应该移动到哪个位置")
    print()
    print("3️⃣  为什么每次都要更新？")
    print("    因为字符可能出现多次，我们需要的是【最新】的位置")
    print("    如果不更新，记录的就是过时的旧位置")
    print()
    print("4️⃣  判断重复的条件：")
    print("    char in char_index  →  这个字符之前出现过")
    print("    char_index[char] >= left  →  上次出现在当前窗口内")
    print("    两个条件都满足 = 在当前窗口内重复")
    print("=" * 80 + "\n")
